<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import Toolbar from '@/widget/Toolbar.vue';
import Index from '@/components/Excel/index.vue';

// 表格数据相关
const tableData = ref([]);
const columns = ref([]);

const ListData = ref([]);
const columnsList = ref([]);
const isInitialized = ref(false); // 避免重复初始化的标志位

// 拖拽数据列表
const dragList = [
  {
    id: 1,
    data: [
      { name: '100000000000000', id: 1, type: 'number', brandId: 1, customerId: 1 },
      { name: '200', id: 2, type: 'number', brandId: 2, customerId: 2 }
    ],
    label: '数据集1'
  },
  {
    id: 2,
    data: [
      { name: '300', id: 3, type: 'number', brandId: 3, customerId: 3 },
      { name: '400', id: 4, type: 'number', brandId: 4, customerId: 4 }
    ],
    label: '数据集2'
  },
  {
    id: 3,
    data: [
      { name: '500', id: 5, type: 'number', brandId: 5, customerId: 5 },
      { name: '600', id: 6, type: 'number', brandId: 6, customerId: 6 }
    ],
    label: '数据集3'
  }
];

/**
 * 初始化表格数据
 */
onMounted(() => {
  // 添加标志位检查，避免重复初始化
  if (!isInitialized.value && columns.value.length === 0) {
    columns.value = [
      { name: 'A' },
      { name: 'B' },
      { name: 'C' },
      { name: 'D' },
      { name: 'E' }
    ];
    columnsList.value = [
      { name: 'A' },
      { name: 'B' },
      { name: 'C' },
      { name: 'D' },
      { name: 'E' }
    ];

    tableData.value = Array.from({ length: 10 }, (_, rowIndex) =>
      columns.value.map((_, colIndex) => ({
        name: rowIndex === 0 && colIndex === 0 ? '示例数据' : ''
      }))
    );
    ListData.value = Array.from({ length: 10 }, (_, rowIndex) =>
      columnsList.value.map((_, colIndex) => ({
        name: rowIndex === 0 && colIndex === 0 ? '示例数据' : ''
      }))
    );

    isInitialized.value = true;
  }
});

/**
 * 处理外部元素拖拽开始事件
 * @param event 拖拽事件
 * @param item 拖拽的数据项
 */
function handleDragStart(event, item) {
  if (event.dataTransfer) {
    // 设置拖拽数据，使用与PcHome兼容的格式
    event.dataTransfer.setData(
      'application/json',
      JSON.stringify({
        type: 'table-cell',
        data: item.data,
        label: item.label
      })
    );
    event.dataTransfer.effectAllowed = 'copy';

    // 设置拖拽视觉效果
    const dragImage = document.createElement('div');

    // 添加截断函数
    const truncateText = (text, maxLength = 4) => {
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    };

    dragImage.textContent = `${item.label}: [${item.data.map((cell) => truncateText(cell.name)).join(', ')}]`;
    dragImage.style.cssText = `
      position: absolute;
      background: #409eff;
      color: white;
      padding: 12px 16px;
      border-radius: 4px;
      font-size: 12px;
      pointer-events: none;
      z-index: -1;
      opacity: 0.8;
    `;

    document.body.appendChild(dragImage);
    event.dataTransfer.setDragImage(dragImage, 0, 0);

    // 清理临时元素
    setTimeout(() => {
      if (dragImage.parentNode) {
        document.body.removeChild(dragImage);
      }
    }, 0);
  }
}

/**
 * 处理表格右键菜单
 * @param rowIndex 行索引
 * @param colIndex 列索引
 * @param allMenus 所有菜单项
 */
const handleContextMenu = (Valeue) => {
  const { allMenus } = Valeue;
  console.log('allMenus:', allMenus);
  // 过滤掉不需要的菜单项
  return allMenus.filter(menu =>
    !['deleteRow', 'deleteColumn'].includes(menu.key)
  );
};
</script>

<template>
  <div class="container">
    <Toolbar
      title="标题标题标题标题标题标题"
      back
      back-txt-color="red"
      right-text="更多"
    />

    <!-- 可拖拽元素区域 -->
    <div
      v-for="item in dragList"
      :key="item.id"
      draggable="true"
      @dragstart="handleDragStart($event, item)"
      class="draggable-element"
      :title="`拖拽${item.label}到表格中`"
    >
      <span class="drag-item-label">{{ item.label }}:</span>
      <span class="drag-item-data">
        <span v-for="(value, index) in item.data" :key="index" class="data-tag">
          {{ value.name }}
        </span>
      </span>
    </div>

    <div class="main">
      <Index
        class="table-container"
        v-model:table-data="tableData"
        v-model:columns="columns"
        :onRightmenu="handleContextMenu"
        :dragging="true"
        :enable-drag="true"
      />

      <Index
        class="table-container"
        v-model:table-data="ListData"
        v-model:columns="columnsList"
        :onRightmenu="handleContextMenu"
        :dragging="true"
        :enable-drag="true"
      />
    </div>
    <div>底部</div>
  </div>
</template>

<style scoped lang="less">
.draggable-element {
  padding: 8px 12px;
  background-color: #ffffff;
  color: #333333;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  cursor: grab;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
  margin: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  font-size: 14px;
}

.draggable-element:hover {
  background-color: #f6f8fa;
  border-color: #0969da;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.drag-item-label {
  font-weight: 600;
  color: #24292f;
}

.data-tag {
  width: 60px;
  height: 35px;
  background-color: #ddf4ff;
  padding: 2px 8px;
  margin-left: 5px;
  text-align: center;
  font-size: 0.8em;
  color: #0969da;
  border: 1px solid #b6e3ff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  line-height: 31px;
  box-sizing: border-box;
}

.table-container {
  width: 600px;
  height: auto;
  margin: 15px;
}
</style>
